package com.wideplay.warp.clustering;

import com.google.inject.Scope;
import com.google.inject.Provider;
import com.google.inject.Key;

import java.lang.annotation.Annotation;

/**
 * Created with IntelliJ IDEA.
 * On: 23/06/2007
 *
 * @author Dhanji R. Prasanna
 * @since 1.0
 */
class GridScope implements Scope {
    private final Class<? extends Annotation> name;

    private GridScope(Class<? extends Annotation> name) {
        this.name = name;
    }

    public <T> Provider<T> scope(Key<T> key, Provider<T> provider) {
        return new FromClusterScopeProvider<T>(key, provider, name);
    }

    static Scope namedClusterScope(Class<? extends Annotation> cluster) {
        return new GridScope(cluster);
    }

    private static class FromClusterScopeProvider<T> implements Provider<T> {
        private final String key;
        private final Provider<T> creator;
        private final Class<? extends Annotation> name;

        public FromClusterScopeProvider(Key<T> key, Provider<T> creator, Class<? extends Annotation> name) {
            this.key = key.toString();
            this.creator = creator;
            this.name = name;
        }
        
        @SuppressWarnings("unchecked")
        public T get() {
            return DataGridService.getCluster(name).get(key, creator);
        }
   }
}
